﻿using System;
using CdcSoftware.Pivotal.Applications.Core.Client;
using CdcSoftware.Pivotal.Engine.Client.Services.Interfaces;
using CdcSoftware.Pivotal.Engine.UI.Forms;
using System.Data;
using System.Windows.Forms;
using CdcSoftware.Pivotal.Applications.Core.Common;

namespace Pcm.Inventory.Client.FormTasks
{
    /// <summary>
    /// The Form Client Task class to undertake some specfic tasks for one business object associated to a specified form.
    /// It will call Form Server Task.
    /// </summary>
    /// <history>
    /// Revision       Date           Author        Description
    /// 6.0.9.0        06/01/2012     VT            Initial Version
    /// </history>
    /// 

    public partial class RE_Stock_Take : FormClientTask
    {

        #region Public methods

        public override void OnFormInitialized()
        {
            try
            {
                this.SharedLoad();
            }
            catch (Exception exc)
            {
                Globals.HandleException(exc, true);
            }
        }

        public override void OnFormReloaded()
        {
            try
            {
                this.SharedLoad();
            }
            catch (Exception exc)
            {
                Globals.HandleException(exc, true);
            }
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Common event for both OnFormInitialised and OnFormReloaded event.
        /// </summary>
        private void SharedLoad()
        {
            try
            {
                //this.EnableDisableAllFields(false);
                this.FormControl.GetControlByName("btnReconcile").Enabled = true;
                this.FormControl.GetControlByName("btnProcess").Enabled = true;
            }
            catch (Exception exc)
            {
                Globals.HandleException(exc, true);
            }
        }

        /// <summary>
        /// Redconsile the stocks.
        /// </summary>
        public void Reconcile()
        {
            try
            {
                DataTable stockDetail = this.DataSet.Tables["RE_Stock_Take_Detail_Stock_Tak"];
                Int16 inventoryActualQuantity = 0;
                DataTable Inventory = null;

                if (stockDetail != null)
                {
                    if (stockDetail.Rows.Count > 0)
                    {
                        for (int i = 0; i < stockDetail.Rows.Count; i++)
                        {
                            inventoryActualQuantity = 0;
                            Inventory = Globals.GetDataTable(InventoryForSKUAndStorageLocationQueryName,
                                                  new object[] { stockDetail.Rows[i][ProductSKUIdFieldName], this.PrimaryDataRow[StorageLocationIdFieldName] }
                                                 , new string[] { QuantityActualFieldName });
                            if (Inventory != null)
                            {
                                if (Inventory.Rows.Count > 0)
                                {
                                    inventoryActualQuantity = TypeConvert.ToInt16(Inventory.Rows[0][QuantityActualFieldName]);
                                    stockDetail.Rows[i][ExistingQuantityFieldName] = inventoryActualQuantity;
                                    stockDetail.Rows[i][VarianceFieldName] = inventoryActualQuantity - TypeConvert.ToInt16(stockDetail.Rows[i][StockTakeQuantityFieldName]);
                                }
                            }
                            this.PrimaryDataRow[Status] = "Reconcile";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        /// <summary>
        /// Method to execute Barcode datafield value changed and populating the SFA_Order_Product secondary
        /// </summary>
        /// <history>
        /// Revision   Date        Author  Description
        /// 6.0.10.1    21/03/2012  DS      Initial Version
        /// </history>
        private void BarcodeValueChanged()
        {
            try
            {
                if (Convert.IsDBNull(this.PrimaryDataRow["Product_Barcode"]))
                    return;

                DataTable productSKU = Globals.GetDataTable("RE Product SKU Barcode is ? LOB ?", new object[] { this.PrimaryDataRow["Product_Barcode"], 
                    this.PrimaryDataRow["Line_Of_Business_Id"]}, "RE_Product_SKU_Id", "Product_Id");

                if (productSKU != null && productSKU.Rows.Count == 1)
                    FetchProductSKU(productSKU);
                else if (productSKU != null && productSKU.Rows.Count > 1)
                    PivotalMessageBox.Show("Multiple Product SKU's found for the keyed in/scanned barcode: " +
                        TypeConvert.ToString(this.PrimaryDataRow["RE_Product_Barcode"]) + Environment.NewLine +
                        "Please contact the Administrator", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                else
                    PivotalMessageBox.Show("No Product SKU record found for the keyed in/scanned barcode.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                //Set the Barcode, Product_Id and SKU as null.
                this.PrimaryDataRow["Product_Barcode"] = DBNull.Value;
                this.FormControl.GetControlByDataName("Product_Barcode").Focus();
            }
            catch (Exception exc)
            {
                Globals.HandleException(exc, true);
            }
        }

        /// <summary>
        /// Fetch Product SKU's
        /// </summary>
        /// <param name="productSKU"></param>
        /// 6.0.10.1    21/03/2012  DS      Initial Version
        public virtual void FetchProductSKU(DataTable productSKU)
        {
            try
            {
                //Calculate the Existing quantity from the Inventory and set it here.
                DataTable inventoryQty = Globals.GetDataTable("RE_Inventory for SKU? Storage Location?", new object[] { productSKU.Rows[0]["RE_Product_SKU_Id"],
                    this.PrimaryDataRow["Storage_Location_Id"] }, "Quantity_Actual");
                if (inventoryQty != null && inventoryQty.Rows.Count == 1)
                {
                    //Add a record to the secondary
                    DataTable stockTakeDetails = this.FormData.DataSet.Tables["RE_Stock_Take_Detail_Stock_Tak"];
                    //Add the sec. row
                    base.NewSecondaryRecord("RE_Stock_Take_Detail_Stock_Tak");
                    DataRow stockTakeDetail = stockTakeDetails.Rows[stockTakeDetails.Rows.Count - 1];
                    stockTakeDetail["Product_SKU_Id"] = productSKU.Rows[0]["RE_Product_SKU_Id"];
                    stockTakeDetail["Product_Id"] = productSKU.Rows[0]["Product_Id"];
                    stockTakeDetail["Storage_Location_Id"] = this.PrimaryDataRow["Storage_Location_Id"];
                    stockTakeDetail["Existing_Quantity"] = inventoryQty.Rows[0]["Quantity_Actual"];

                    stockTakeDetail["Stock_Take_Quantity"] = 1;
                    //If quantity is less than Inventory quantity then assign the quantity as 0, stockTakeDetail["Quantity"] = 0;


                }
                else if (inventoryQty != null && inventoryQty.Rows.Count > 1)
                    PivotalMessageBox.Show("Multiple Inventory record found for the SKU and Storage Location. Please contact System Administrator.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                else
                    PivotalMessageBox.Show("No Inventory record found for the SKU and Storage Location.", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception exc)
            {
                Globals.HandleException(exc, true);
            }
        }
        #endregion
    }
}
